//
//  EmailRegistViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/7/19.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "EmailRegistViewController.h"
#import "AgreementViewController.h"
@interface EmailRegistViewController ()<UITextViewDelegate>
{
    NSString * message;
}
@property (nonatomic,strong)NSString *captcha_id;//图形验证码ID
@end

@implementation EmailRegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = TABLEVIEWLCOLOR;
  
    _nextView.backgroundColor = self.view.backgroundColor;
    _nextView.frame = CGRectMake( UIScreenWidth, 0, UIScreenWidth, UIScreenHeight - RealValue_W(142));
    _nextView.hidden = YES;
    [self.view addSubview:_nextView];
    //    第一步
    [self initFirestUI];
   
    [self captchaWithNumber:[EXUnit getNowTimeTimestamp]];
  
    //    第二步
    [self initNextUI];
}
- (void)initLable:(UILabel *)lable font:(UIFont *)font
{
    lable.font = font;
    lable.textColor = MAINTITLECOLOR1;
    lable.attributedText = [EXUnit finderattributedString:Localized(@"no_number_quick_logon") attributedString:Localized(@"no_Login_Now") color:TABTITLECOLOR font:font];
}
- (void)initTextField:(UITextField *)textField placeholder:(NSString *)placeholder
{
    textField.placeholder = placeholder;
    [textField setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
    textField.tintColor = TABTITLECOLOR;
    textField.textColor = MAINTITLECOLOR;
    textField.font = AutoBoldFont(15);
    
}
- (void)initFirestUI
{
    WeakSelf
    _lineview.backgroundColor = CELLCOLOR;
    [self initTextField:_phoneField placeholder:Localized(@"register_Mailbox_message")];
    
    [_nextButton setTitle:Localized(@"Security_Next_step") forState:UIControlStateNormal];
    _nextButton.backgroundColor = TABTITLECOLOR;
    _nextButton.titleLabel.font = AutoBoldFont(16);
    KViewRadius(self.nextButton, 2);
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        [weakSelf dismissAnimation];
        
    }];
    _loginlable.userInteractionEnabled = YES;
    [_loginlable addGestureRecognizer:tap];
    
    RACSignal*phone=[_phoneField.rac_textSignal map:^id(NSString* value) {
        return @(value.length>0);
    }];
    
    RACSignal*loginSignal=[RACSignal combineLatest:@[phone] reduce:^id(NSNumber*phoneValid){
        return @([phoneValid boolValue]);
    }];
    
    [loginSignal subscribeNext:^(NSNumber* x) {
        
        if ([x boolValue]) {
            weakSelf.nextButton.enabled=YES;
            weakSelf.nextButton.alpha = 1;
            weakSelf.nextButton.backgroundColor = TABTITLECOLOR;
            [weakSelf.nextButton setTitleColor:[UIColor whiteColor] forState:0];
        }else{
            weakSelf.nextButton.enabled=NO;
            weakSelf.nextButton.alpha = 1;
            weakSelf.nextButton.backgroundColor = [ZBLocalized sharedInstance].buttonNormalStatus;
            [weakSelf.nextButton setTitleColor:ColorStr(@"#AAAAAA") forState:0];
        }
    }]; 
}
- (void)initNextUI
{
    WeakSelf
    _nextlineView.backgroundColor = CELLCOLOR;
    _nextlineView1.backgroundColor = CELLCOLOR;
    _nextlineView2.backgroundColor = CELLCOLOR;
    _nextlineView3.backgroundColor = CELLCOLOR;
     _nextlineView4.backgroundColor = CELLCOLOR;
    [self initTextField:_iconCodeField placeholder:Localized(@"register_graphic_verification_code_message")];
    [self initTextField:_verificationField placeholder:Localized(@"register_verification_code")];
    // 倒计时的时长
    _verificationCodeBtn.title = Localized(@"register_get_Mailbox_verification_code");
    _verificationCodeBtn.totalSecond = 60;
     _verificationCodeBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    _verificationCodeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_verificationCodeBtn setTitleColor:TABTITLECOLOR forState:0];
    [_verificationCodeBtn processBlock:^(NSUInteger second)
     {
         weakSelf.verificationCodeBtn.title = [NSString stringWithFormat:@"%lis", (unsigned long)second] ;
     } onFinishedBlock:^{  // 倒计时完毕
         weakSelf.verificationCodeBtn.title = Localized(@"Regain_validation_code");
     }];
    [self initTextField:_passwordField placeholder:Localized(@"login_password_message")];
    [self initTextField:_agginPWField placeholder:Localized(@"register_Confirm_password")];
    
    if ([AppDelegate shareAppdelegate].recommend_code_force.integerValue ==1)
    {
        [self initTextField:_InvitationField placeholder:Localized(@"register_sure_Invitation_code")];
        
    }else
    {
        [self initTextField:_InvitationField placeholder:Localized(@"register_Invitation_code")];
    }
    [_registButton setTitle:Localized(@"register") forState:UIControlStateNormal];
    _registButton.backgroundColor = TABTITLECOLOR;
    _registButton.titleLabel.font = AutoBoldFont(16);
    KViewRadius(self.registButton, 2);
    
    weakSelf.iconCodeImage.userInteractionEnabled = YES;
    weakSelf.iconCodeImage.backgroundColor = WHITECOLOR;
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageBtnClick)];
    [weakSelf.iconCodeImage addGestureRecognizer:tapGes];

    RACSignal*validPswSignal=[_passwordField.rac_textSignal map:^id(NSString* value) {
        return @(value.length>PassworldLastlength && value.length<Passworldhighlength);
    }];
    RACSignal*iconCodeSignal=[_iconCodeField.rac_textSignal map:^id(NSString* value) {
        return @(value.length ==6);
    }];
    RACSignal*agginPWSignal=[_agginPWField.rac_textSignal map:^id(NSString* value) {
        return @(value.length>PassworldLastlength && value.length<Passworldhighlength);
    }];
    RACSignal*verificationSignal=[_verificationField.rac_textSignal map:^id(NSString* value) {
        return @(value.length>0);
    }];
    
    RACSignal*loginSignal=[RACSignal combineLatest:@[validPswSignal,agginPWSignal,verificationSignal,iconCodeSignal] reduce:^id(NSNumber*pswValid,NSNumber*agginValue,NSNumber*verificationValid,NSNumber*iconCodeValid){
        return @([pswValid boolValue]&&[agginValue boolValue]&&[verificationValid boolValue]&&[iconCodeValid boolValue]);
    }];
    
    [loginSignal subscribeNext:^(NSNumber* x) {
        
        if ([x boolValue]) {
            weakSelf.registButton.enabled=YES;
            weakSelf.registButton.alpha = 1;
            weakSelf.registButton.backgroundColor = TABTITLECOLOR;
            [weakSelf.registButton setTitleColor:[UIColor whiteColor] forState:0];
        }else{
            weakSelf.registButton.enabled=NO;
            weakSelf.registButton.alpha = 1;
            weakSelf.registButton.backgroundColor = [ZBLocalized sharedInstance].buttonNormalStatus;
            [weakSelf.registButton setTitleColor:ColorStr(@"#AAAAAA") forState:0];
        }
    }];
    message = Localized(@"register_agreement");
    _agreementTextView = [[UITextView alloc]initWithFrame:CGRectMake(26,
                                                                     0,
                                                                     UIScreenWidth- 60,
                                                                     40)];
    // 设置属性
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    // 设置行间距
    paragraphStyle.paragraphSpacing = 2; // 段落间距
    paragraphStyle.lineSpacing = 1;      // 行间距
    NSDictionary *attributes = @{
                                 NSForegroundColorAttributeName:[UIColor blackColor],
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:message attributes:attributes];
    [attrStr addAttributes:@{
                             NSLinkAttributeName:Localized(@"registration_protocol")
                             }
                     range:[message rangeOfString:Localized(@"registration_protocol")]];
    
    _agreementTextView.linkTextAttributes = @{NSForegroundColorAttributeName:TABTITLECOLOR}; // 修改可点击文字的颜色
    _agreementTextView.attributedText = attrStr;
    _agreementTextView.editable = NO;
    _agreementTextView.scrollEnabled = NO;
    _agreementTextView.delegate = self;
    _agreementTextView.backgroundColor = [UIColor clearColor];
    _agreementTextView.textColor = MAINTITLECOLOR1;
    _agreementTextView.textAlignment = NSTextAlignmentLeft;
    
    [_nextView addSubview:_agreementTextView];
    
    if (_emailType == RegistEmailType) {
        _loginlable.hidden = NO;
        _agreementTextView.hidden = NO;
        _InvitationField.hidden = NO;
        _nextlineView3.hidden = NO;
        _passwordField.placeholder = Localized(@"login_password_message");
        [_registButton setTitle:Localized(@"register") forState:0];
        _loginlable.hidden = NO;
        _nextLoginlable.hidden = NO;
    }else
    {
        _loginlable.hidden = YES;
        _agreementTextView.hidden = YES;
        _InvitationField.hidden = YES;
        _nextlineView3.hidden = YES;
        [_registButton setTitle:Localized(@"submit") forState:0];
        _passwordField.placeholder = Localized(@"register_new_password_message");
        _nextLoginlable.hidden = YES;
        _loginlable.hidden = YES;
        [self performSelector:@selector(modifyConstant) withObject:nil afterDelay:0.1];//延迟加载,执行
    }
    [_InvitationField setValue:SystemBlodFont(13) forKeyPath:@"_placeholderLabel.font"];
    [_passwordField setValue:SystemBlodFont(13) forKeyPath:@"_placeholderLabel.font"];
    [_phoneField setValue:SystemBlodFont(13) forKeyPath:@"_placeholderLabel.font"];
    [_iconCodeField setValue:SystemBlodFont(13) forKeyPath:@"_placeholderLabel.font"];
    [_agginPWField setValue:SystemBlodFont(13) forKeyPath:@"_placeholderLabel.font"];
    [_verificationField setValue:SystemBlodFont(13) forKeyPath:@"_placeholderLabel.font"];
    _verificationCodeBtn.titleLabel.font = AutoFont(13);
    [self initLable:_loginlable font:AutoFont(13)];
    [self initLable:_nextLoginlable font:AutoFont(13)];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        [weakSelf dismissAnimation];
        
    }];
    _nextLoginlable.userInteractionEnabled = YES;
    [_nextLoginlable addGestureRecognizer:tap];
}
- (void)modifyConstant
{
    self.top.constant -=88;
}
- (void)viewDidLayoutSubviews
{
     _agreementTextView.mj_y = _nextlineView3.mj_y +20;
}
// 其他方式修改
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    
    NSRange range = [message rangeOfString:Localized(@"registration_protocol")];

    if (characterRange.location == range.location) {
        AgreementViewController * AgreementVC = [AgreementViewController alloc];
        [self presentViewController:AgreementVC animated:YES completion:nil];
    }
    
    return YES;
}
- (IBAction)openbutton:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    self.passwordField.secureTextEntry = !self.passwordField.secureTextEntry;
  
}
//重新获取图像验证码
- (void)tapImageBtnClick
{
    [self captchaWithNumber:[EXUnit getNowTimeTimestamp]];
}
/*
 *
 *  获取图形验证码
 */
- (void)captchaWithNumber:(NSString *)timeStr
{
    WeakSelf
    [self GETWithHost:@"" path:captchaHttp param:@{} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"code"] integerValue] ==0)//成功
        {
            weakSelf.captcha_id = responseObject[@"result"][@"id"];
           NSString * img =[NSString stringWithFormat:@"%@captcha/%@.png?reload=%@",HOST_IP,responseObject[@"result"][@"id"],timeStr];
            [weakSelf.iconCodeImage sd_setImageWithURL:[NSURL URLWithString:img]];
            
        }else
        {
            [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
/*
 *** 发送验证码
 */
- (IBAction)verificationButton:(QCCountdownButton *)sender {
    
    if (![NSString isEmailString:_phoneField.text])
    {
        if ([NSString isEmptyString:_phoneField.text]) {
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"register_mailbox_empty_message") view:kWindow];
        }else
        {
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"register_Mailbox_format_message") view:kWindow];
        }
        
    }else if (_iconCodeField.text.length ==0)
    {
        
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"register_graphic_verification_code_message") view:kWindow];
        
    }else
    {
       [self.verificationCodeBtn startTime];
        WeakSelf
        NSNumber *  use_type;
        if (_emailType ==RegistEmailType) {
            
            use_type = @(0);
        }else
        {
            use_type = @(2);
        }
    
        [self POSTWithHost:@"" path:SMSHttp param:@{@"username":_phoneField.text,@"use_type":use_type,@"id":weakSelf.captcha_id,@"img_code":_iconCodeField.text} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if ([responseObject[@"code"] integerValue] ==0)//成功
            {
                
               
            }else
            {
                 [self captchaWithNumber:[EXUnit getNowTimeTimestamp]];
                [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
            }
            
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}
- (IBAction)nextButton:(LcButton *)sender;
{
    if (![NSString isEmailString:_phoneField.text]) {
        
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"register_Mailbox_format_message") view:kWindow];
         [sender stopAnimation];
        return;
    }
    WeakSelf
    [UIView transitionWithView:self.nextView duration:0.3 options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                        weakSelf.nextView.hidden = NO;
                        weakSelf.nextView.mj_x = 0;
                        
                    }
                    completion:^(BOOL finish){
                        
                    }];
}
/*
 *重新找回密码
 */
- (void)getPassword:(LcButton *)sender
{
    if (![NSString isEmailString:_phoneField.text]) {
         [sender stopAnimation];
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"register_Mailbox_format_message") view:kWindow];
    }else if (![EXUnit CodeissSixplace:_verificationField.text]) {
        
        [EXUnit showMessage:Localized(@"VerificationMessage")];
        [sender stopAnimation];
    }else if (![EXUnit judgePassWordLegal:_passwordField.text])
    {
         [sender stopAnimation];
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"login_Illegal_password") view:kWindow];
    }else if (![_passwordField.text isEqualToString:_agginPWField.text])
    {
         [sender stopAnimation];
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"register_two_password_inconsistent_message") view:kWindow];
        
    }else
    {
        WeakSelf
        [self POSTWithHost:@"" path:forgetPasswordHttp param:@{@"username":_phoneField.text,@"code":_verificationField.text,@"password":_passwordField.text,@"password_confirmation":_agginPWField.text} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              [sender stopAnimation];
            if ([responseObject[@"code"] integerValue] ==0)//成功
            {
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
                [weakSelf dismissAnimation];
            }else
            {
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
            }
            
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             [sender stopAnimation];
        }];
    }
}
- (IBAction)registButton:(LcButton *)sender {
    
    if (_emailType == RegistEmailType) {
       
        [self subimt:sender];
    }else
    {
       
        [self getPassword:sender];
    }
}
/*
 *** 注册
 */
- (void)subimt:(LcButton *)sender
{
    if (![NSString isEmailString:_phoneField.text]) {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"register_mailbox_empty_message") view:kWindow];
        [sender stopAnimation];
    }else if (![EXUnit CodeissSixplace:_verificationField.text]) {
        
        [EXUnit showMessage:Localized(@"VerificationMessage")];
        [sender stopAnimation];
    }else if (![EXUnit judgePassWordLegal:_passwordField.text])
    {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"login_Illegal_password") view:kWindow];
        [sender stopAnimation];
    }else if (![_passwordField.text isEqualToString:_agginPWField.text])
    {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"register_two_password_inconsistent_message") view:kWindow];
        [sender stopAnimation];
        
    }else if ([AppDelegate shareAppdelegate].recommend_code_force.integerValue ==1 &&[NSString isEmptyString:_InvitationField.text])
    {
        
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"register_sure_Invitation_code_mes") view:kWindow];
        [sender stopAnimation];
    }else
    {
        
        [self POSTWithHost:@"" path:registerHttp param:@{@"username":_phoneField.text,
                                                         @"password":_passwordField.text,
                                                         @"code":_verificationField.text,
                                                         @"password_confirmation":_agginPWField.text,
                                                         @"country_id":@"",
                                                         @"recommend_code":[NSString isEmptyString:_InvitationField.text]?@"":_InvitationField.text
                                                         } cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                                             
                                                             if ([responseObject[@"code"] integerValue] ==0)//成功
                                                             {
                                                                 [self jsonAnalyticData:responseObject[@"result"]];
                                                                 
                                                             }else
                                                             {
                                                                 [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
                                                             }
                                                             [sender stopAnimation];
                                                         } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                                             [sender stopAnimation];
                                                             
                                                         }];
    }
}
//数据解析
- (void)jsonAnalyticData:(NSDictionary *)dic
{
    [AppDelegate shareAppdelegate].isBecomeActive = NO;
    [EXUserManager saveUserInfo:[EXUser mj_objectWithKeyValues:dic]];

    //  记住账号和密码
    NSMutableDictionary *usernamepasswordKVPairs = [NSMutableDictionary dictionary];
    [usernamepasswordKVPairs setObject:_phoneField.text forKey:KEY_USERNAME];
    [CHKeychain save:KEY_USERNAME_PASSWORD data:usernamepasswordKVPairs];
    //    储存登录变量
    [EXUserManager savelogin:@"1"];

    NSArray * dataArray1  = @[[EXUserManager userInfo].token,@"ios"];
    NSData *data1 = [EXUnit NSJSONSerializationWithmethod:@"server.auth" parameter:dataArray1 id:1763];
    [[SocketRocketUtility instance] sendData:data1];    // 发送数据
    [[NSNotificationCenter defaultCenter]postNotificationName:LoginSusessNotificationse object:nil];
    [EXUserManager getbindInfo:^(BOOL isSuccess) {
        [self getUserInfo];
    }];
   
}
- (void)getUserInfo
{
    UIViewController *vc = self;
    while (vc.presentingViewController) {
        vc = vc.presentingViewController;
    }
    CATransition *animation = [CATransition animation];
    animation.duration = 1.0;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = @"rippleEffect";
    //animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromRight;
    [self.view.window.layer addAnimation:animation forKey:nil];
    [vc dismissViewControllerAnimated:YES completion:nil];
}
- (void)dismissAnimation
{
    CATransition *animation = [CATransition animation];
    animation.duration = 1.0;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = @"rippleEffect";
    //animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromRight;
    [self.view.window.layer addAnimation:animation forKey:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
